from datetime import datetime
from flask_login import UserMixin
from extensions import db


class Device(db.Model):
    __tablename__ = "devices"

    id = db.Column(db.Integer, primary_key=True)
    ip = db.Column(db.String(15), unique=True, nullable=False)
    name = db.Column(db.String(50), nullable=False)
    username = db.Column(db.String(50), nullable=True)
    passwd = db.Column(db.String(50), nullable=True)
    status = db.Column(db.String(10), default="离线")  # 修改默认状态为"离线"
    cpu_usage = db.Column(db.Integer, default=0)
    last_seen = db.Column(db.DateTime)
    snmp_community = db.Column(db.String(50), default="public")  # SNMP团体名
    device_type = db.Column(db.String(20), default="switch")  # 设备类型
    is_monitored = db.Column(db.Boolean, default=True)  # 是否监控
    group_id = db.Column(db.Integer, db.ForeignKey("device_group.id"))

    # 关系定义（级联删除）
    history = db.relationship(
        "DeviceHistory", backref="device", lazy="dynamic", cascade="all, delete-orphan"
    )

    def __repr__(self):
        return f"<Device {self.name} ({self.ip})>"


class DeviceGroup(db.Model):
    __tablename__ = "device_group"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True)
    description = db.Column(db.Text)

    # 关系定义（级联删除）
    devices = db.relationship(
        "Device", backref="group", lazy="dynamic", cascade="all, delete-orphan"
    )


class DeviceHistory(db.Model):
    __tablename__ = "device_history"

    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.Integer, db.ForeignKey("devices.id", ondelete="CASCADE"))
    cpu_usage = db.Column(db.Integer)
    timestamp = db.Column(
        db.DateTime, default=datetime.utcnow, index=True
    )  # 添加索引提高查询效率


class User(db.Model, UserMixin):
    __tablename__ = "users"
    __table_args__ = {'extend_existing': True}  # Allow extending the existing table definition

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(100), nullable=False)
    is_admin = db.Column(db.Boolean, default=False)
    last_login = db.Column(db.DateTime)  # 新增最后登录时间

    def verify_password(self, password):
        """密码验证方法"""
        from werkzeug.security import check_password_hash

        return check_password_hash(self.password, password)
